import React from 'react';
import PropTypes from 'prop-types';
import { Form, Input, Modal } from 'antd';

const FormItem = Form.Item;

const styles = {
	input: {
		marginBottom: '0'
	}
};

const formItemLayout = {
	labelCol: {
		span: 6,
	},
	wrapperCol: {
		span: 14,
	},
	style: styles.input
};

class MyModal extends React.Component {

	state = { name: '', error: '' }

	onOk = () => {
		const { onOk } = this.props;
		const { error, name } = this.state;
		const d = {
			name,
			remark: '',
			parentCategoryId: 0
		};
		if (!name) {
			this.setState({
				error: '请输入产品品类'
			});
			return;
		}
		if (!name || error) return;
		this.setState({ name: '', error: '' });
		onOk(d);
	}

	change = e => {
		const { list, data } = this.props;
		const state = {
			name: e.target.value
		};
		state.error = list.find(t => t.name === state.name && t.id !== data.id) ? '产品品类已存在' : null;
		state.error = !state.error && !state.name ? '请输入产品品类' : state.error;
		state.error = !state.error && !/^[\u4e00-\u9fa5a-zA-Z0-9]{1,30}$/.test(state.name) ? '最多输入30个字符，只能输入中文、数字或英文字母' : state.error;
		this.setState(state);
	}

	render() {
		const { name, error } = this.state;
		const { data, handleCancel } = this.props;
		const visible = data && !data.id;
		return (
			<Modal
				title={'新增品类'}
				visible={visible}
				onOk={this.onOk}
				onCancel={() => { this.setState({ name: '', error: '' }); handleCancel(); }}
			>
				<Form layout="horizontal">
					<FormItem label="产品品类" hasFeedback {...formItemLayout} required help={error} validateStatus={error ? 'error' : null}>
						<Input style={styles.input} onChange={this.change} value={name} />
					</FormItem>
				</Form>
			</Modal>
		);
	}
}

MyModal.propTypes = {
	data: PropTypes.object,
	onOk: PropTypes.func,
	handleCancel: PropTypes.func,
};

export default MyModal;
